package com.unlcn.ils.wms.web.controller.borrow;

import cn.huiyunche.commons.constant.QiniuConstant;
import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.QiniuUtil;
import com.unlcn.ils.wms.backend.service.borrow.WmsBorrowCarService;
import com.unlcn.ils.wms.backend.service.inbound.AsnOrderService;
import com.unlcn.ils.wms.base.dto.BorrowDetailDTO;
import com.unlcn.ils.wms.base.dto.BorrowHistoryDTO;
import com.unlcn.ils.wms.base.dto.BorrowPrintDetailDTO;
import com.unlcn.ils.wms.base.model.stock.WmsBorrowCar;
import com.unlcn.ils.wms.base.model.stock.WmsBorrowCarDetail;
import com.unlcn.ils.wms.web.vo.borrow.BorrowHistoryVo;
import com.unlcn.ils.wms.web.vo.borrow.WmsBorrowCarVo;
import jodd.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2017/10/20.
 */
@RestController
@RequestMapping("/borrow")
public class WmsBorrowCarController {

    private Logger LOGGER = LoggerFactory.getLogger(WmsBorrowCarController.class);

    @Autowired
    private WmsBorrowCarService wmsBorrowCarService;
    @Autowired
    AsnOrderService asnOrderService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    /**
     * 借用登记列表
     * @param wmsBorrowCarVo
     * @return
     */
    @RequestMapping(value = "/borrowLine", method = RequestMethod.POST)
    public ResultDTO<Object> borrowLine(@RequestBody WmsBorrowCarVo wmsBorrowCarVo) {
        LOGGER.info("WmsBorrowCarController.borrowLine param: {}" + wmsBorrowCarVo.toString());
        ResultDTO resultDTO = null;

        try {
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("limitStart", wmsBorrowCarVo.getStartIndex());
            paramsMap.put("limitEnd", wmsBorrowCarVo.getPageSize());
            paramsMap.put("deleteFlag", 1);
            paramsMap.put("orderByClause", " wb.gmt_create desc ");

            // 借用人姓名
            if (!StringUtil.isEmpty(wmsBorrowCarVo.getBcBorrowName())) {
                paramsMap.put("bcBorrowName", wmsBorrowCarVo.getBcBorrowName());
            }
            // 借用人部门
            if (!StringUtil.isEmpty(wmsBorrowCarVo.getBcBorrowDepartment())) {
                paramsMap.put("bcBorrowDepartment", wmsBorrowCarVo.getBcBorrowDepartment());
            }
            // 借用起始时间
            if (wmsBorrowCarVo.getBorrowStartTime() != null) {
                paramsMap.put("borrowStartTime", wmsBorrowCarVo.getBorrowStartTime());
            }
            // 借用截止时间
            if (wmsBorrowCarVo.getBorrowEndTime() != null) {
                paramsMap.put("borrowEndTime", wmsBorrowCarVo.getBorrowEndTime());
            }
            // 所属部门
            if (!StringUtil.isEmpty(wmsBorrowCarVo.getBcWhcode())) {
                paramsMap.put("bcWhcode", wmsBorrowCarVo.getBcWhcode());
            }

            // 查询借用登记数据
            List<WmsBorrowCar> wmsBorrowCarList = wmsBorrowCarService.borrowLine(paramsMap);
            // 借用登记数据统计
            Integer count = wmsBorrowCarService.borrowLineCount(paramsMap);

            wmsBorrowCarVo.setTotalRecord(count);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("totalRecord", wmsBorrowCarVo.getTotalRecord());
            map.put("totalPage", wmsBorrowCarVo.getTotalPage());
            map.put("pageNo", wmsBorrowCarVo.getPageNo());
            map.put("pageSize", wmsBorrowCarVo.getPageSize());
            map.put("wmsBorrowCarList", wmsBorrowCarList);

            resultDTO = new ResultDTO<Object>(true, map, "成功获取借用登记列表");
        }catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.borrowLine businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.borrowLine error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 借车记录列表
     * @param borrowHistoryVo
     * @return
     */
    @RequestMapping(value = "/borrowHistoryLine", method = RequestMethod.POST)
    public ResultDTO<Object> borrowHistoryLine(@RequestBody BorrowHistoryVo borrowHistoryVo) {
        LOGGER.info("WmsBorrowCarController.borrowHistoryLine param: {}" + borrowHistoryVo.toString());
        ResultDTO resultDTO = null;

        try {
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("limitStart", borrowHistoryVo.getStartIndex());
            paramsMap.put("limitEnd", borrowHistoryVo.getPageSize());
            paramsMap.put("orderByClause", " wbcd.gmt_create desc ");

            // 车架号
            if (!StringUtil.isEmpty(borrowHistoryVo.getVin())) {
                paramsMap.put("vin", borrowHistoryVo.getVin());
            }
            // 是否还车
            if (borrowHistoryVo.getIsReturn() != null) {
                paramsMap.put("isReturn", borrowHistoryVo.getIsReturn());
            }
            // 借用人姓名
            if (!StringUtil.isEmpty(borrowHistoryVo.getBorrowName())) {
                paramsMap.put("borrowName", borrowHistoryVo.getBorrowName());
            }
            // 还车人姓名
            if (!StringUtil.isEmpty(borrowHistoryVo.getReturnName())) {
                paramsMap.put("returnName", borrowHistoryVo.getReturnName());
            }
            // 借用起始时间
            if (borrowHistoryVo.getReturnStartTime() != null) {
                paramsMap.put("returnStartTime", borrowHistoryVo.getReturnStartTime());
            }
            // 借用截止时间
            if (borrowHistoryVo.getReturnEndTime() != null) {
                paramsMap.put("returnEndTime", borrowHistoryVo.getReturnEndTime());
            }
            // 所属部门
            if (!StringUtil.isEmpty(borrowHistoryVo.getBcWhcode())) {
                paramsMap.put("bcWhcode", borrowHistoryVo.getBcWhcode());
            }

            // 查询借用登记数据
            List<BorrowHistoryDTO> borrowHistoryList = wmsBorrowCarService.borrowHistoryLine(paramsMap);
            // 借用登记数据统计
            Integer count = wmsBorrowCarService.borrowHistoryLineCount(paramsMap);

            borrowHistoryVo.setTotalRecord(count);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("totalRecord", borrowHistoryVo.getTotalRecord());
            map.put("totalPage", borrowHistoryVo.getTotalPage());
            map.put("pageNo", borrowHistoryVo.getPageNo());
            map.put("pageSize", borrowHistoryVo.getPageSize());
            map.put("wmsBorrowCarList", borrowHistoryList);

            resultDTO = new ResultDTO<Object>(true, map, "成功获取借车记录列表");
        }catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.borrowHistoryLine businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.borrowHistoryLine error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 查询借车单明细
     * @param borrowId
     * @return
     */
    @RequestMapping(value = "/findBorrowDetail/{borrowId}", method = RequestMethod.GET)
    public ResultDTO<Object> findBorrowDetail(@PathVariable  String borrowId) {
        LOGGER.info("WmsBorrowCarController.findBorrowDetail param: {}" + borrowId);
        ResultDTO resultDTO = null;

        try {
            List<WmsBorrowCarDetail> wmsBorrowCarDetailList = wmsBorrowCarService.findBorrowDetail(Long.valueOf(borrowId));
            resultDTO = new ResultDTO<Object>(true, wmsBorrowCarDetailList, "成功查询借车单明细");
        }catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.borrowHistoryLine businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.borrowHistoryLine error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 查询编辑的信息
     * @param bcId
     * @return
     */
    @RequestMapping(value = "/queryModifyDetail/{bcId}", method = RequestMethod.GET)
    public ResultDTO<Object> queryModifyDetail(@PathVariable  Long bcId) {
        LOGGER.info("WmsBorrowCarController.queryModifyDetail param: {}" + bcId);
        ResultDTO resultDTO = null;

        try {
            List<BorrowDetailDTO> borrowDetailList = wmsBorrowCarService.queryModifyDetail(bcId);
            resultDTO = new ResultDTO<Object>(true, borrowDetailList, "成功获取编辑信息");
        }catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.queryModifyDetail businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.queryModifyDetail error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 新增借车单
     * @param wmsBorrowCarVo
     * @return
     */
    @RequestMapping(value="/add" , method = RequestMethod.POST)
    public ResultDTO add(@RequestBody  WmsBorrowCarVo wmsBorrowCarVo, HttpServletRequest request) {
        LOGGER.info("WmsBorrowCarController.add param: {}" + wmsBorrowCarVo.toString());
        ResultDTO<Object> resultDTO = null;

        try {
            List<WmsBorrowCarDetail> wmsBorrowCarDetailList = wmsBorrowCarVo.getWmsBorrowCarDetailList();
            if (CollectionUtils.isEmpty(wmsBorrowCarDetailList))
                throw new BusinessException("车辆信息不能为空!");
            if (StringUtils.isEmpty(wmsBorrowCarVo.getUploadKey()))
                throw new BusinessException("上传凭证不能空!");

//            Boolean sameVinAndColor = false;
//            for (int i=0; wmsBorrowCarDetailList.size()>i; i++) {
//                WmsBorrowCarDetail wmsBorrowCarDetail1 = wmsBorrowCarDetailList.get(i);
//                for (int j=0; wmsBorrowCarDetailList.size()>j; j++) {
//                    WmsBorrowCarDetail wmsBorrowCarDetail2 = wmsBorrowCarDetailList.get(j);
//                    if (i != j) {
//                        if (wmsBorrowCarDetail1.getBdCarSpecname().equals(wmsBorrowCarDetail2.getBdCarSpecname())
//                                && wmsBorrowCarDetail1.getBdCarColorname().equals(wmsBorrowCarDetail2.getBdCarColorname())) {
//                            sameVinAndColor = true;
//                            break;
//                        }
//                    }
//                }
//            }
//
//            if (sameVinAndColor == true) {
//                throw new BusinessException("车型和颜色不能相同!");
//            }

            // 获取操作人id
            String userId = request.getHeader("userId");

            WmsBorrowCar wmsBorrowCar = new WmsBorrowCar();
            BeanUtils.copyProperties(wmsBorrowCarVo, wmsBorrowCar);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if (!StringUtil.isEmpty(wmsBorrowCarVo.getBcBorrowDate())) {
                Date bcBorrowDate = format.parse(wmsBorrowCarVo.getBcBorrowDate());
                wmsBorrowCar.setBcBorrowDate(bcBorrowDate);
            }
            if (!StringUtil.isEmpty(wmsBorrowCarVo.getBcEstimatedReturnDate())) {
                Date bcEstimatedReturnDate = format.parse(wmsBorrowCarVo.getBcEstimatedReturnDate());
                wmsBorrowCar.setBcEstimatedReturnDate(bcEstimatedReturnDate);
            }
            wmsBorrowCarService.add(wmsBorrowCar, wmsBorrowCarVo.getWmsBorrowCarDetailList(), Long.valueOf(userId));
            resultDTO = new ResultDTO<Object>(true, "成功新增!");
        } catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarControllerb.add businessException: {}", e);
            resultDTO = new ResultDTO<Object>(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.add error: {}", e);
            resultDTO = new ResultDTO<Object>(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 编辑借车单
     * @param wmsBorrowCarVo
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public ResultDTO modify(@RequestBody  WmsBorrowCarVo wmsBorrowCarVo) {
        LOGGER.info("WmsBorrowCarController.modify param: {}" + wmsBorrowCarVo.toString());
        ResultDTO<Object> resultDTO = null;

        try {
            if (wmsBorrowCarVo.getBcId() == null)
                throw new BusinessException("id不能为空!");
            if (CollectionUtils.isEmpty(wmsBorrowCarVo.getWmsBorrowCarDetailList()))
                throw new BusinessException("车辆信息不能为空!");

            List<WmsBorrowCarDetail> wmsBorrowCarDetailList = wmsBorrowCarVo.getWmsBorrowCarDetailList();

//            Boolean sameVinAndColor = false;
//            for (int i=0; wmsBorrowCarDetailList.size()>i; i++) {
//                WmsBorrowCarDetail wmsBorrowCarDetail1 = wmsBorrowCarDetailList.get(i);
//                for (int j=0; wmsBorrowCarDetailList.size()>j; j++) {
//                    WmsBorrowCarDetail wmsBorrowCarDetail2 = wmsBorrowCarDetailList.get(j);
//                    if (i != j) {
//                        if (wmsBorrowCarDetail1.getBdCarSpecname().equals(wmsBorrowCarDetail2.getBdCarSpecname())
//                                && wmsBorrowCarDetail1.getBdCarColorname().equals(wmsBorrowCarDetail2.getBdCarColorname())) {
//                            sameVinAndColor = true;
//                            break;
//                        }
//                    }
//                }
//            }

//            if (sameVinAndColor == true) {
//                throw new BusinessException("车型和颜色不能相同!");
//            }

            WmsBorrowCar wmsBorrowCar = new WmsBorrowCar();
            BeanUtils.copyProperties(wmsBorrowCarVo, wmsBorrowCar);
            wmsBorrowCarService.modify(wmsBorrowCar, wmsBorrowCarVo.getWmsBorrowCarDetailList());
            resultDTO = new ResultDTO<Object>(true, "成功编辑!");
        } catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.modify businessException: {}", e);
            resultDTO = new ResultDTO<Object>(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.modify error: {}", e);
            resultDTO = new ResultDTO<Object>(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 删除借车单
     * @param rcId
     * @return
     */
    @RequestMapping(value="/del")
    public ResultDTO del(@RequestBody Long[] rcId) {
        LOGGER.info("WmsBorrowCarController.del param: {}" + rcId);
        ResultDTO<Object> resultDTO = null;

        try {
            if (rcId == null)
                throw new BusinessException("借车单id不能为空!");

            wmsBorrowCarService.delete(Arrays.asList(rcId));
            resultDTO = new ResultDTO<Object>(true, "成功删除!");
        } catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.del usinessException: {}", e);
            resultDTO = new ResultDTO<Object>(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.del error: {}", "系统异常...");
            resultDTO = new ResultDTO<Object>(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 生成打印信息
     * @param bcId
     * @return
     */
    @RequestMapping(value="/printInfo/{bcId}", method = RequestMethod.GET)
    public ResultDTO printInfo(@PathVariable Long bcId) {
        LOGGER.info("WmsBorrowCarController.printInfo param: {}" + bcId);
        ResultDTO<Object> resultDTO = null;

        try {
            if (bcId == null)
                throw new BusinessException("借车单id不能为空!");

            BorrowPrintDetailDTO borrowPrintDetailDTO = wmsBorrowCarService.printInfo(bcId);
            resultDTO = new ResultDTO<Object>(true, borrowPrintDetailDTO, "成功获取打印信息!");
        } catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.printInfo usinessException: {}", e);
            resultDTO = new ResultDTO<Object>(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.printInfo error: {}", e);
            resultDTO = new ResultDTO<Object>(false, "系统异常...");
        }

        return resultDTO;
    }

    @RequestMapping(value="/getUploadToken", method = RequestMethod.GET)
    public ResultDTO getUploadToken() {
        LOGGER.info("WmsBorrowCarController.getUploadToken");
        ResultDTO<Object> resultDTO = null;

        try {
            String token = QiniuUtil.generateSimpleUploadToken();
            resultDTO = new ResultDTO<Object>(true, token, "成功获取上传token!");
        } catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.getUploadToken usinessException: {}", e);
            resultDTO = new ResultDTO<Object>(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.getUploadToken error: {}", e);
            resultDTO = new ResultDTO<Object>(false, "系统异常...");
        }

        return resultDTO;
    }

    @RequestMapping(value="/getDownUrl/{key}", method = RequestMethod.GET)
    public ResultDTO getDownUrl(@PathVariable("key") String key) {
        LOGGER.info("WmsBorrowCarController.getDownUrl param {}" + key);
        ResultDTO<Object> resultDTO = null;

        try {
//            String downloadURL = QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_BUCKET, key, "", null, null);
            String downloadURL = QiniuUtil.generateDownloadURL(key, "");
            resultDTO = new ResultDTO<Object>(true, downloadURL, "成功获取!");
        } catch (BusinessException e) {
            LOGGER.error("WmsBorrowCarController.getDownUrl usinessException: {}", e);
            resultDTO = new ResultDTO<Object>(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsBorrowCarController.getDownUrl error: {}", e);
            resultDTO = new ResultDTO<Object>(false, "系统异常...");
        }

        return resultDTO;
    }
}
